package com.bing.task.google;

import com.bing.utils.GoogleIps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by kaibb on 15-11-25.
 */
public class Search {
    private static final Logger LOGGER = LoggerFactory.getLogger(Search.class);
    private ExecutorService executorService = Executors.newFixedThreadPool(20);
    private static volatile boolean running = false;


    public void execute() {
        int i = 0;
        List<Future<InetSocketAddress>> result = new ArrayList<>();
        out:
        for (String s : GoogleIps.getIPS()) {
            i++;
            Future<InetSocketAddress> submit80 = executorService.submit(new SearchIP(new InetSocketAddress(s, 80)));
            result.add(submit80);
            Future<InetSocketAddress> submit443 = executorService.submit(new SearchIP(new InetSocketAddress(s, 443)));
            result.add(submit443);
            if (i % 100 == 0) {
                for (Future<InetSocketAddress> future : result) {
                    try {
                        InetSocketAddress inetSocketAddress = future.get();
                        if (inetSocketAddress != null) {
                            LOGGER.info("找到可用google IP:{}", inetSocketAddress);
                            Files.write(Paths.get("google.ips"), inetSocketAddress.toString().getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE);
                            break out;
                        }
                    } catch (Exception e) {
                        LOGGER.error("", e);
                    }
                }
            }

        }
    }

    public static void start() {
        if (running) {
            LOGGER.info("Search Google Host is running......");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Search search = new Search();
                running = true;
                search.execute();
                running = false;
            }
        }).start();
    }

}
